var map, markersLayer, vectorLayer, animator;
function mapInit() {
    var vecLayer = new Geo.View2D.Layer.XYZ("高德矢量", [
        "http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x=${x}&y=${y}&z=${z}",
        "http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x=${x}&y=${y}&z=${z}",
        "http://webrd03.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x=${x}&y=${y}&z=${z}",
        "http://webrd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x=${x}&y=${y}&z=${z}"
    ], {
        isBaseLayer: true,
        visibility: true,
        displayInLayerSwitcher: true
    });
    map = new OpenLayers.Map("map", {
        projection: "EPSG:900913",
        displayProjection: "EPSG:4326",
        units: 'm',
        numZoomLevels: 19
    });
    map.addLayer(vecLayer);
    // google地图需要转换坐标
    var lonLat = new OpenLayers.LonLat(115.46333, 35.262358);
    lonLat.transform(map.displayProjection, map.getProjectionObject());
    map.setCenter(lonLat, 11);
    map.addControl(new OpenLayers.Control.MousePosition());
    markersLayer = new Geo.View2D.Layer.GeoMarkers("GeoMarkers");
    map.addLayer(markersLayer);
    //创建矢量图层
    vectorLayer = new Geo.View2D.Layer.Vector("moveLayer");
    //添加图层
    map.addLayer(vectorLayer);

    //设置地图最小缩放级别为17级
    map.events.register("zoomend", this, function (e) {
        if (map.getZoom() < 8) {
            //map.zoomTo(17);
            map.setCenter(lonLat, 8);
        }
    });
}

//添加地物标注
function addMarker(lon, lat, str) {
    //自定义标签
    var html = "<div style='background-color: #aac5ee;padding:2px;border:1px solid #adb09b;word-break:keep-all;white-space:nowrap;'>"
        + str + "</div>";
    var tag = new Geo.View2D.MarkerTag(html);
    tag.offset = new Geo.Pixel(-(tag.size.w / 2), -tag.size.h - 25);
    //图标icon
    var url = baseURL + "/statics/plugins/map/img/marker_red.png";
    var size = new Geo.Size(19, 25);
    var offset = new Geo.Pixel(-(size.w / 2), -size.h);
    var icon = new Geo.View2D.Icon(url, size, offset);
    // google地图需要转换坐标
    var lonLat = new Geo.LonLat(lon, lat);
    lonLat.transform(map.displayProjection, map.getProjectionObject());
    //标注
    var geoMarker = new Geo.GeoMarker(lonLat, icon, tag)
    markersLayer.addMarker(geoMarker);
}

//删除地物标注
function mapClear() {
    deleteMarker();
    if (vectorLayer) {
        vectorLayer.removeFeatures(vectorLayer.features);
    }
}

function deleteMarker() {
    var markers = markersLayer.markers;
    if (markers.length != 0) {
        for (var l = 0; l < markers.length; l++) {
            markersLayer.removeMarker(markers[l]);
        }
        deleteMarker();
    }
}

function reset() {
    mapClear();
    $('#chepaihao').val('');
    $('#starttime').val('');
    $('#endtime').val('');
}

var state = 0;
//循环任务
//    AOS.task(function() {
//        if (state == 0) {
//            realTimeLocation();
//        }
//    }, 10000);
setInterval(function(){ if(state ==0) {realTimeLocation();console.log("定时任务执行中.....")}}, 10000);

//实时标注位置
function realTimeLocation() {
    $.ajax({
        type:"POST",
        dataType:"json",
        url: baseURL+'location/listReportLocation',
        success: function (data,textStatus) {
            mapClear();
            $.each(data.list,(index,item)=>{
                addMarker(item.lon, item.lat, item.plate_number);
            });
        }
    });
    state = 0;
}

//实时定位
function getLocationList() {
    $('#chepaihao').val('');
    $('#starttime').val('');
    $('#endtime').val('');
    // google地图需要转换坐标
    var lonLat = new OpenLayers.LonLat(115.46333, 35.262358);
    lonLat.transform(map.displayProjection, map.getProjectionObject());
    map.setCenter(lonLat, 11);
    realTimeLocation();
}

function getTrailList() {
    var starttime = $('#starttime').val();
    var endtime = $('#endtime').val();
    var chepaihao = $('#chepaihao').val();
    if (!chepaihao) {
        alert('请输入查询车牌号码！');
        return;
    }
    if (!starttime) {
        alert('请选择轨迹开始时间！');
        return;
    }
    if (!endtime) {
        alert('请选择轨迹结束时间！');
        return;
    }
    var data = {"starttime": starttime, "endtime": endtime, "chepaihao": chepaihao};
    state = 1;
    $.ajax({
        type: "POST",
        data: JSON.stringify(data),
        url: baseURL + 'location/getTrailList',
        dataType: "json",
        contentType: "application/json",
        success: function (data, textStatus) {
            if (data.code == 0) {
                var points = [];
                $.each(data.list, (index, item) => {
                    var lonLat = new Geo.LonLat(item.lon,item.lat);
                    lonLat.transform(map.displayProjection, map.getProjectionObject());
                    points.push(new Geo.Geometry.Point(lonLat.lon,lonLat.lat));
                });
                if (data.list.length > 0) {
                    paintTrack(points);
                }
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}

function paintTrack(points) {
    //创建移动的轨迹线路
    var trackLine = new Geo.Feature.Vector(new Geo.Geometry.LineString(
        points), null, {
        strokeColor: 'red',
        strokeWidth: 3
    });
    //创建移动的要素点
    var movePoint = new Geo.Feature.Vector(points[0], null, {
        externalGraphic: Geo.Util.getImagesLocation() + "car.png",
        graphicWidth: 20.75,
        graphicHeight: 46
    });
    vectorLayer.addFeatures([trackLine, movePoint]);
    animator = new Geo.Animator();
    //设置动画要素
    animator.setFeature(movePoint);
    //设置动画线路和移动速度
    animator.moveAlong(trackLine, {
        ratio: 0.5
    });

    trackMove();
}

function trackMove() {
    //判断如果动画要素在起点，则开始移动动画要素
    if (animator.isAtStart()) {
        animator.start();
    }
}

$(function () {
    $('.form_date').datetimepicker({
        language: 'zh-CN', //语言设置
        format: 'yyyy-mm-dd hh:ii:ss', //日期格式
        weekStart: 1,  // 默认值：0 ,一周从哪一天开始。0（星期日）到6（星期六）
        autoclose: true, //Boolean. 默认值：false,当选择一个日期之后是否立即关闭此日期时间选择器。
        startView: 2, //Number, String. 默认值：2, 'month',0:小时，1:天，2:月，3:年，4十年
        minView: 0,   //Number, String. 默认值：0, 'hour',日期时间选择器所能够提供的最精确的时间选择视图。
        maxView: 4,    //Number, String. 默认值：4, 'decade' 日期时间选择器最高能展示的选择范围视图。
        todayBtn: true, //默认值: false,显示当天按钮
        todayHighlight: true, //默认值: false ，今日高亮
        minuteStep: 1, //分钟时显示的时间间隔，此处设置为1分钟
        forceParse: false //默认值: true,当选择器关闭的时候，是否强制解析输入框中的值
    });
    mapInit();
});